package fr.insalyon.sims.broadcast.tests;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;

import fr.insalyon.sims.SIMSImageUtils;

import java.util.Date;


    public class SIMSScreenCapture {

    public static long framerateDelay = 500;
    private static String format = "jpg";
    private static String ipDestination = "127.0.0.1";
    private static int portDestination = 22593;
    
    
    
    
    static private void envoyer(Socket connexion, byte[] sendOctets) {
        try {
            DataOutputStream fluxReseau = new DataOutputStream(connexion.getOutputStream());
            fluxReseau.write(sendOctets);
            //fluxRéseau.write(sendOctets);
            
        } 
            catch (IOException ex) {
            System.out.println("Probleme avec le serveur");
        }
    }
    
  /** pad a string S with a size of N with character 0
     /**
  ** on the left (True) or on the right(false)
  **/
  public static String stringPaddingLeftZero( String s, int n) {
    StringBuffer str = new StringBuffer(s);
    int strLength  = str.length();
      for ( int i = 0; i <= n-strLength; i ++ ) {
        if ( i < n - strLength ) str.insert( 0, '0');
      }
    return str.toString();
  }
    
    
    
    public static void main(String[] args){
    System.out.println(new Date());
    
        try{
            Socket connexion = new Socket(ipDestination, portDestination);
            // determine le taille courante du screen
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Dimension screenSize = toolkit.getScreenSize();
            Rectangle screenRect = new Rectangle(screenSize);
            //creer le screenshot
            Robot robot = new Robot();
            int i;int i_min=10;int i_max=20;
            long max = 0;
            long min = 999999;
            long sum = 0;
            int tailleImage = 0;
            
            Date timeStart_total = new Date();
            for(i=i_min;i<i_max;i++){
                Date timeStart = new Date();
                
                //attente pour s'accorder avec le framerate
                long screenshotDelay = 0;
                if(i!=i_min && (framerateDelay >= (sum/(1 + i - i_min))) ){
                    Thread.sleep(framerateDelay - (sum/(1 + i - i_min)));
                }
                //on calcule la durée de capture de l'ecran et de l'envoi de l'image
                Date timeShotStart = new Date();
                BufferedImage image = robot.createScreenCapture(screenRect);
                
                // sauvegarde de l'image vers un fichier "bmp"
                /*File fichier = new File("D:\\INSA_07-08\\projets\\SIMS\\screen\\test"+i+"."+format);
                ImageIO.write(image, format, fichier);*/
                ByteArrayOutputStream object = new ByteArrayOutputStream();
                    ImageIO.write(image, format, object);
                byte[] octets = object.toByteArray();
                if(i==i_min){
                    tailleImage = object.size();
                }
                //FileInputStream photo = new FileInputStream(fichier);
                /*ObjectInputStream photo = new ObjectInputStream(object);
                byte[] octets = new byte[(int)fichier.length()];
                photo.read(octets);
                */
                //calcul du numero de l'image
//                String numeroImage = (new Integer(i)).toString();
//                numeroImage = stringPaddingLeftZero( numeroImage, 8);
//                String tailleImageStr = stringPaddingLeftZero((new Integer(tailleImage)).toString(), 8);
//                System.out.println("\n numeroImage="+ numeroImage);
//                System.out.println("\n taille image="+  tailleImageStr);
//                
//                byte[] sendOctets = new byte[16 + tailleImage];
//                byte[] enteteBytes = (numeroImage+tailleImageStr).getBytes();    
//                System.arraycopy(enteteBytes, 0, sendOctets, 0, 16);
//                System.arraycopy(octets, 0, sendOctets, 16, tailleImage);
//                // envoie de la chaine de bytes
                envoyer(connexion,SIMSImageUtils.getByteArrayFromBufferedImage(i, format, false, image));
                // mesures de performances
                Date timeEnd = new Date();
                long time = (timeEnd.getTime() - timeShotStart.getTime());
                System.out.println(format+"["+i+"] : "+ time);
                sum += time;
                if(time > max){max = time;}
                if(time < min){min = time;}
            }
            // mesures de performances
            Date timeEnd_total = new Date();
            System.out.println("\n Moyenne total="+ (timeEnd_total.getTime() - timeStart_total.getTime())/(i_max - i_min) );
            System.out.println("Maxi : "+(max));
            System.out.println("Mini : "+(min));
            connexion.close();
            
            // simulation de mouvement de souris et de clique de souris. La classe robot fait bokou de chose:-)!
            //robot.mouseMove(30,70);
            /*robot.mousePress(InputEvent.BUTTON1_MASK);
            robot.mousePress(InputEvent.BUTTON1_MASK);*/
        }
        catch(AWTException e){ System.out.println("Erreur AWT\n");}
        catch(IOException e){ System.out.println("Erreur IO\n");}
        catch(java.lang.InterruptedException e){ System.out.println("Erreur Interrupted\n");}
        

    System.out.println(new Date());
    }
}
